//
//  DeviceListViewController.m
//  BMS
//
//  Created by 颜魏 on 2024/12/9.
//

#import "DeviceListViewController.h"
#import "BTManager.h"
#import "ProgressHUD.h"

@interface DeviceListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) BTManager *btManager;
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *dataSource;
@property (nonatomic, assign) BOOL isPushed;
@property (nonatomic, assign) BOOL isHaveAuth;
@property (nonatomic, strong) NSMutableDictionary *diviceNameDict;

@end

@implementation DeviceListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = NSLocalizedString(@"Device List", nil);
    self.btManager = [BTManager sharedBTManager];
    self.dataSource = [[NSMutableArray alloc] init];
    self.diviceNameDict = [[NSMutableDictionary alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevices:) name:kBTSearchDevices object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:kBTConnectionSucceed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevicesName:) name:kBTSearchDevicesName object:nil];

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.dataSource addObjectsFromArray:[BTManager sharedBTManager].peripherals];
    [self.tableView reloadData];
    if (!self.dataSource.count) {
        [self.btManager disconnectRootPeripheral];
        [self.btManager retartScan];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isPushed = NO;
    [BTManager sharedBTManager].isGettingBattery = NO;
    [self.btManager retartScan];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [BTManager sharedBTManager].isGettingBattery = NO;
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - notification
- (void)searchDevicesName:(NSNotification *)nf {
    NSMutableDictionary *dict = nf.object;
    [self.diviceNameDict addEntriesFromDictionary:dict];
    [self.tableView reloadData];
}

- (void)searchDevices:(NSNotification *)nf {
    NSArray *list = nf.object;
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:list];
    [self.tableView reloadData];
}

- (void)connectSuccess {
    [ProgressHUD hideHUD];
    if (!self.isPushed) {
        self.isPushed = YES;
        [self.navigationController popViewControllerAnimated:true];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    [cell.contentView.subviews performSelector:@selector(removeFromSuperview)];
    cell.backgroundColor = self.tableView.backgroundColor;
    cell.contentView.backgroundColor = self.tableView.backgroundColor;
    NSString *name = [self.diviceNameDict objectForKey:self.dataSource[indexPath.row].name];
    cell.textLabel.text = name.length>0 ? name : self.dataSource[indexPath.row].name;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont  systemFontOfSize:16];
    
//    if ([[BTManager sharedBTManager] peripheral] && [[[BTManager sharedBTManager] peripheral].name isEqualToString:self.dataSource[indexPath.row].name]) {
//        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//        UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 0, kWidth-180, 50)];
//        descLabel.textAlignment = NSTextAlignmentRight;
//        descLabel.textColor = [UIColor redColor];
//        descLabel.font = [UIFont systemFontOfSize:14];
//        descLabel.text = NSLocalizedString(@"Connected", nil);
//        [cell.contentView addSubview:descLabel];
//    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.btManager stopScan];
//    [ProgressHUD showSuccessMessage:self.dataSource[indexPath.row].name];
    [BTManager sharedBTManager].isGettingBattery = NO;
    for (NSInteger i=0; i<self.dataSource.count; i++) {
        [self.btManager disconnectPeripheral:self.dataSource[i]];
    }
    [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Connecting", nil) timer:10];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.btManager connectPeripheral:self.dataSource[indexPath.row]];
    });
}


@end
